# route.py
from typing import Optional

from fastapi import APIRouter
from fastapi.responses import JSONResponse

from source.module import Manager, logging

from .generate_js import generate_js_file
from .model import SiteItemUpdate
from .module import SiteItem

router = APIRouter(prefix="/sites", tags=["Site Nav"])


class SiteNavRoute:
    def __init__(self, manager: Manager, db_obj: SiteItem):
        self.db_obj = db_obj
        self.manager = manager

    def setup_routes(self):
        @router.get(
            "",
            summary="Get Site Items",
            description="获取所有网站",
            response_class=JSONResponse,
        )
        async def get_sites(category: str = "index"):
            logging(None, f"start get sites for category: {category}")
            return await self.db_obj.all(category)

        @router.post(
            "",
            summary="Save Site Item",
            description="保存网站",
            response_class=JSONResponse,
        )
        async def save_site_item(site_item: SiteItemUpdate, id: Optional[str] = None):
            if id:
                exist_item = await self.db_obj.select(id)
                if exist_item:
                    await self.db_obj.update(id, **site_item.model_dump(exclude_unset=True))
                else:
                    return {"code": 1001, "message": "Site item not found"}
            else:
                await self.db_obj.add(**site_item.model_dump())

            return {"code": 200, "message": "Site item saved successfully"}

        @router.delete(
            "/{id_}",
            summary="Delete Site Item",
            description="删除指定ID的网站",
            tags=["Site Nav"],
            response_class=JSONResponse,
        )
        async def delete_site_item(id_: str):
            await self.db_obj.delete(id_)
            return {"code": 200, "message": "Site item deleted successfully"}

        @router.get(
            "/generate",
            summary="Generate Sites JS File",
            description="生成网站js文件",
            response_class=JSONResponse,
        )
        async def generate_sites(category: str = "index"):
            import os

            dict_items = await self.db_obj.all(category)

            # 生成 JS 文件
            download_folder = self.manager.folder
            output_file = os.path.join(download_folder, category + ".js")
            generate_js_file(category, dict_items, output_file)
            return {"code": 200, "data": [category + ".js"]}

        @router.get(
            "/fetch_metadata",
            summary="Fetch Metadata from URL",
            description="Fetches title, description, and logo from the given URL",
            tags=["Site Nav"],
            response_class=JSONResponse,
        )
        async def fetch_metadata(url: str):
            from .site_metadata import fetch_metadata_from_url

            return {"code": 200, "data": await fetch_metadata_from_url(url)}

        return router
